package com.pro.common.service.pay.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pro.common.service.pay.service.unit.PaymentUnitService;
import com.pro.framework.api.util.StrUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "支付回调统一入口")
@RestController
@RequestMapping("/")
@Slf4j
public class PayCallbackController {

    @Autowired
    private PaymentUnitService paymentUnitService;

    @Operation(summary = "支付回调")
    @RequestMapping(value = "/payment/{merchantCode}/notify", produces = "application/json;charset=UTF-8", method = {RequestMethod.GET, RequestMethod.POST})
    public synchronized ResponseEntity<?> paymentNotify(
            @PathVariable("merchantCode") String merchantCode,
            @RequestParam(required = false) Map<String, Object> paramMap,
            @RequestBody(required = false) String requestBody) {
        return ResponseEntity.ok(paymentUnitService.paymentNotify(merchantCode, this.readParams(paramMap, requestBody)));
    }

    private String readParams(Map<String, Object> map, String requestBody) {
        if (map == null) {
            map = new HashMap<>();
        }
        if (StrUtils.isNotBlank(requestBody) && JSONUtil.isTypeJSON(requestBody)) {
            JSONObject jo = JSONUtil.parseObj(requestBody);
            map.putAll(jo);
        }
        return JSONUtil.toJsonStr(map);
    }
}
